{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# About Homework"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# About Pascal's triangle\n",
    "# Recursive Way\n",
    "def pascal_triangle1(i, j):\n",
    "    assert i >= j >= 0\n",
    "    if j == 0 or i == j:\n",
    "        return 1\n",
    "    else:\n",
    "        j = min(j, i - j)\n",
    "        return pascal_triangle1(i-1, j-1) + pascal_triangle1(i-1, j)\n",
    "print(pascal_triangle1(10, 2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dynamic Programming\n",
    "def pascal_triangle2(i, j):\n",
    "    assert i >= j >= 0\n",
    "    \n",
    "    if j == 0 or i == j:\n",
    "        return 1\n",
    "    \n",
    "    j = min(j, i - j)\n",
    "    numlist = [0] * (j + 1)\n",
    "    numlist[0] = 1\n",
    "  \n",
    "    for x in range(1, i+1):\n",
    "        for y in range(j, 0, -1):\n",
    "            numlist[y] = numlist[y] + numlist[y-1]\n",
    "    return numlist[j]\n",
    "\n",
    "print(pascal_triangle2(5, 2))        \n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use Equation\n",
    "# For large numbers, not correct\n",
    "import math\n",
    "def pascal_triangle3(i, j):\n",
    "    assert i >= j >= 0\n",
    "    if j == 0 or i == j:\n",
    "        return 1\n",
    "    else:\n",
    "        j = min(j, i - j)\n",
    "        return int(math.factorial(i) / (math.factorial(j) * math.factorial(i - j)))\n",
    "\n",
    "print(pascal_triangle3(5, 2))                        \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from operator import mul    # or mul=lambda x,y:x*y\n",
    "from fractions import Fraction\n",
    "from functools import reduce\n",
    "\n",
    "def pascal_triangle4(i,j): \n",
    "    assert i >= j >= 0\n",
    "    if j == 0 or i == j:\n",
    "        return 1\n",
    "    else:\n",
    "        j = min(j, i - j)\n",
    "        return int( reduce(mul, (Fraction(i-t, t+1) for t in range(j)), 1) )\n",
    "print(pascal_triangle4(10, 2))  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Do a simple test\n",
    "\n",
    "funcList = [pascal_triangle1, pascal_triangle2,\n",
    "            pascal_triangle3, pascal_triangle4]\n",
    "for i in range(5, 20):\n",
    "    for j in range(0, int(i / 2)):\n",
    "        retSet = set()\n",
    "        print(\"(%d, %d)\" % (i, j))\n",
    "        for func in funcList:\n",
    "            retSet.add(func(i, j))\n",
    "        if len(retSet) != 1:\n",
    "            raise Exception(\"Error, Results are not the same!\")\n",
    "        print(\"Result:\", retSet.pop())\n",
    "print(\"Done!\")       \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# measure calc time\n",
    "n = 20\n",
    "k = 10\n",
    "print(\"Recursive\", pascal_triangle1(n, k))\n",
    "%timeit pascal_triangle1(n, k)\n",
    "\n",
    "print(\"Dynamic Programming\",pascal_triangle2(n, k))\n",
    "%timeit pascal_triangle2(n, k)\n",
    "\n",
    "print(\"Use Equation\", pascal_triangle3(n, k))\n",
    "%timeit pascal_triangle3(n, k)\n",
    "\n",
    "print(\"Use Equation and Fraction\", pascal_triangle4(n, k))\n",
    "%timeit pascal_triangle4(n, k)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 200\n",
    "k = 100\n",
    "# print(\"Recursive\", pascal_triangle1(n, k))\n",
    "# %timeit pascal_triangle1(n, k)\n",
    "\n",
    "print(\"Dynamic Programming\\t\\t\",pascal_triangle2(n, k))\n",
    "%timeit pascal_triangle2(n, k)\n",
    "\n",
    "print(\"Use Equation\\t\\t\\t\", pascal_triangle3(n, k))  # not correct\n",
    "%timeit pascal_triangle3(n, k)\n",
    "\n",
    "print(\"Use Equation and Fraction\\t\", pascal_triangle4(n, k))\n",
    "%timeit pascal_triangle4(n, k)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sympy\n",
    "n = 20000\n",
    "k = 10050\n",
    "# print(\"Recursive\", pascal_triangle1(n, k))\n",
    "# %timeit pascal_triangle1(n, k)\n",
    "\n",
    "# print(\"Dynamic Programming\\t\\t\",pascal_triangle2(n, k))\n",
    "# %timeit pascal_triangle2(n, k)\n",
    "\n",
    "# print(\"Use Equation\\t\\t\\t\", pascal_triangle3(n, k))\n",
    "# %timeit pascal_triangle3(n, k)\n",
    "\n",
    "num1 = pascal_triangle4(n, k)\n",
    "print(\"Use Equation and Fraction\\t\")\n",
    "%timeit pascal_triangle4(n, k)\n",
    "\n",
    "# Use sympy.binomial\n",
    "# Source Code:\n",
    "# https://docs.sympy.org/latest/_modules/sympy/functions/combinatorial/factorials.html#binomial\n",
    "num2 = int(sympy.binomial(n, k))\n",
    "print(\"Use sympy module\\t\")\n",
    "%timeit sympy.binomial(n, k)\n",
    "\n",
    "print(\"\\nAre they the same? \", num1 == num2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in range(17):\n",
    "    print(' '.join('%5d'%pascal_triangle4(n,k) for k in range(n+1)).center(100))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Homework: About Frac Class"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Frac(object):\n",
    "    def __init__(self, num, denom):\n",
    "        g = math.gcd(num, denom)\n",
    "        self.__num = num / g\n",
    "        self.__denom = denom / g\n",
    "    def __str__(self):\n",
    "        return \"Frac <\" + str(int(self.__num)) + \", \" + str(int(self.__denom)) + \">\"\n",
    "\n",
    "a = Frac(99, -22)\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How to use modules"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# in file module_example.py\n",
    "def print_info():\n",
    "    print(\"Hello World\")\n",
    "    \n",
    "class TestClass(object):    \n",
    "    num = 0\n",
    "    def __init__(self, num):\n",
    "        self.num = num\n",
    "    \n",
    "    def doSth(self):\n",
    "        print(self.num)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# in file module_test1.py\n",
    "import module_example\n",
    "if __name__ == \"__main__\":\n",
    "    module_example.print_info() \n",
    "    \n",
    "    a = module_example.TestClass(20)\n",
    "    a.doSth()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# in file module_test1.py\n",
    "# Note: don't need module_example. as prefix\n",
    "from module_example import *\n",
    "if __name__ == \"__main__\":\n",
    "    print_info() \n",
    "    \n",
    "    a = TestClass(20)\n",
    "    a.doSth()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Date and Time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get current date and time\n",
    "from datetime import datetime\n",
    "now = datetime.now()\n",
    "print(now)\n",
    "\n",
    "dt = datetime(1949, 10, 1, 10, 0)\n",
    "print(dt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# PIL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!conda install pillow\n",
    "# if not work, try the following line\n",
    "#!conda install --channel conda-forge pillow=5.2.0\n",
    "from PIL import Image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load an image\n",
    "im = Image.open('lena.png')\n",
    "# Show the image\n",
    "im.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# rotate\n",
    "print(im.format, im.size)\n",
    "out = im.transpose(Image.ROTATE_90)\n",
    "print(out.format, out.size)\n",
    "out.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Resize\n",
    "im_big = im.resize((400, 400))\n",
    "print(im_big.format, im_big.size)\n",
    "im_big.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# split channels\n",
    "r, g, b = im.split()\n",
    "r.show()\n",
    "g.show()\n",
    "b.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# merge 3 channels\n",
    "im2 = Image.merge(\"RGB\", [b, g, r])\n",
    "im2.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from PIL import ImageFilter\n",
    "im3 = im.filter(ImageFilter.BLUR)\n",
    "im3.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Screen Shot\n",
    "from PIL import ImageGrab\n",
    "\n",
    "#get current screen copy\n",
    "image = ImageGrab.grab()\n",
    "\n",
    "#display image size\n",
    "print(\"Current screen shot size :\",image.size)\n",
    "\n",
    "#display image mode\n",
    "print(\"Screen shot picture mode :\", image.mode)\n",
    "\n",
    "#save picture to screen_grab.bmp\n",
    "image.save('screen_grab.bmp')\n",
    "\n",
    "#show picture\n",
    "image.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get an Internet Image and show it\n",
    "import requests\n",
    "\n",
    "im = Image.open(requests.get(\"http://vi.ustc.edu.cn/_upload/article/images/6b/84/90ccbd7841ecabfc9e1dfad23577/W020110428465080158055.gif\", stream=True).raw)\n",
    "print(im.format, im.size)\n",
    "\n",
    "out = im.transpose(Image.ROTATE_90)\n",
    "out.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 强大的Numpy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [ 5, 6, 7, 8]\n",
    "b = np.array(a)\n",
    "\n",
    "print(b.size, b.shape, b.ndim, b.dtype)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "array_zeros = np.zeros([4 , 4])\n",
    "array_ones = np.ones([5, 5])\n",
    "array_eye = np.eye(5)\n",
    "\n",
    "print(array_zeros)\n",
    "print(array_ones)\n",
    "print(array_eye)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "matrix = np.random.rand(5, 6)\n",
    "print(matrix.size, matrix.shape, matrix.dtype)\n",
    "print(matrix)\n",
    "\n",
    "# 矩阵转置\n",
    "matrixT = matrix.T\n",
    "print(matrixT.size, matrixT.shape, matrixT.dtype)\n",
    "print(matrixT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sub_matrix = matrix[1:4, 2:4]\n",
    "print(sub_matrix)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ma = np.random.rand(3, 3)\n",
    "mb = np.random.rand(3, 3)\n",
    "print(ma)\n",
    "print(mb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# matrix operations\n",
    "print(\"Shape:\",ma.shape) # print the matrix shape\n",
    "print(\"Shape:\",mb.shape) # print the matrix shape\n",
    "print(\"Sum:\",ma+mb) # matrix sum\n",
    "print(\"Elementwise multiplication:\",ma*mb) # elementwise multiplication\n",
    "print(\"Power of two:\",ma**2) # power of two\n",
    "print(\"Matrix multiplication:\",ma.dot(mb)) # product\n",
    "print(\"Minimum:\",ma.min()) # minumum\n",
    "print(\"Maximum:\",mb.max()) # maximum\n",
    "print(\"Sum:\",mb.sum()) #sum \n",
    "print(\"Mean:\",ma.mean()) # mean"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Matplotlib 画图\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#折线图\n",
    "year = [2011, 2012, 2013, 2014, 2015]\n",
    "pop = [1.2, 3.5, 6.7, 8.0, 9.1]\n",
    "\n",
    "plt.plot(year, pop)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 散点图\n",
    "plt.scatter(year, pop)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 直方图\n",
    "values = [0,1,2,3,4,1,2,3,4,4,5,2,4,1]\n",
    "# 直方图绘制函数，bins为直方图间隔份数\n",
    "plt.hist(values,bins=10)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 多个子图\n",
    "def f(t):\n",
    "    return np.exp(-t) * np.cos(2 * np.pi * t)\n",
    "\n",
    "t1 = np.arange(0, 5, 0.1)\n",
    "t2 = np.arange(0, 5, 0.02)\n",
    "\n",
    "plt.figure(12)\n",
    "plt.subplot(221)\n",
    "plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')\n",
    "\n",
    "plt.subplot(222)\n",
    "plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')\n",
    "\n",
    "plt.subplot(212)\n",
    "plt.plot([1, 2, 3, 4], [1, 4, 9, 16])\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "fig = plt.figure()\n",
    "ax = fig.add_subplot(111, projection='3d')\n",
    "X = [1, 1, 2, 2]\n",
    "Y = [3, 4, 4, 3]\n",
    "Z = [1, 2, 1, 1]\n",
    "ax.plot_trisurf(X, Y, Z)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 画心\n",
    "# Story:\n",
    "# https://baijiahao.baidu.com/s?id=1606866687044231987&wfr=spider&for=pc\n",
    "    \n",
    "t = np.arange(0,2*np.pi, 0.1)\n",
    "x = 16*np.sin(t)**3\n",
    "y = 13*np.cos(t)-5*np.cos(2*t)-2*np.cos(3*t)-np.cos(4*t)\n",
    "plt.plot(x,y)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Show an internet image\n",
    "import matplotlib.image as mpimg\n",
    "img = mpimg.imread(\"https://sta.36krcnd.com/common-module/common-header/images/logo-a6afc.png\")\n",
    "imgplot = plt.imshow(img)\n",
    "type(img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# OpenCV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!conda install opencv -c conda-forge\n",
    "import cv2\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(cv2.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img = cv2.imread(\"lena.png\")\n",
    "print(img.shape)\n",
    "\n",
    "plt.imshow(img)\n",
    "plt.show()\n",
    "\n",
    "# cv2.namedWindow('Lena')\n",
    "# cv2.imshow('Lena',img)\n",
    "# cv2.waitKey()\n",
    "# cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 色彩恢复\n",
    "img2=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n",
    "plt.imshow(img2)\n",
    "plt.show()\n",
    "\n",
    "# cv2.imwrite(\"newlena.jpg\", img2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_g=cv2.GaussianBlur(img2,(7,7),3)\n",
    "plt.imshow(img_g)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img_gray=cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)\n",
    "print(img_gray.shape)\n",
    "plt.imshow(img_gray,cmap='gray') #cmap='gray' is required to show the image correctly\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# edge detection\n",
    "img_canny = cv2.Canny(img2,180,200)\n",
    "plt.imshow(img_canny,cmap='gray')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(type(img2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Treat matrix as an image\n",
    "# You can operate \n",
    "img3 = img2 * 2\n",
    "plt.imshow(img3)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Translation\n",
    "import numpy as np\n",
    "rows, cols, chs = img2.shape\n",
    "print(rows, cols, chs)\n",
    "M = np.float32([[1,0,100],[0,1,50]])\n",
    "dst = cv2.warpAffine(img2,M,(cols,rows))\n",
    "\n",
    "plt.imshow(dst)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Rotation\n",
    "R = cv2.getRotationMatrix2D(((cols-1)/2.0,(rows-1)/2.0),45,1)\n",
    "dst = cv2.warpAffine(img2,R,(cols,rows))\n",
    "\n",
    "plt.imshow(dst)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Hough Line\n",
    "# https://docs.opencv.org/3.4/d6/d10/tutorial_py_houghlines.html\n",
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "img = cv2.imread('sudoku.jpg')\n",
    "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "edges = cv2.Canny(gray,50,150,apertureSize = 3)\n",
    "lines = cv2.HoughLines(edges,1,np.pi/180,200)\n",
    "for line in lines:\n",
    "    rho,theta = line[0]\n",
    "    a = np.cos(theta)\n",
    "    b = np.sin(theta)\n",
    "    x0 = a*rho\n",
    "    y0 = b*rho\n",
    "    x1 = int(x0 + 1000*(-b))\n",
    "    y1 = int(y0 + 1000*(a))\n",
    "    x2 = int(x0 - 1000*(-b))\n",
    "    y2 = int(y0 - 1000*(a))\n",
    "    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)\n",
    "\n",
    "plt.imshow(img)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use GrabCut for foreground Extraction\n",
    "# https://docs.opencv.org/3.4/d8/d83/tutorial_py_grabcut.html\n",
    "\n",
    "imgori = cv2.imread('messi5.jpg')\n",
    "img = cv2.cvtColor(imgori, cv2.COLOR_BGR2RGB)\n",
    "plt.imshow(img)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mask = np.zeros(img.shape[:2],np.uint8)\n",
    "bgdModel = np.zeros((1,65),np.float64)\n",
    "fgdModel = np.zeros((1,65),np.float64)\n",
    "rect = (50,50,450,290)\n",
    "cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)\n",
    "mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')\n",
    "img = img*mask2[:,:,np.newaxis]\n",
    "\n",
    "plt.imshow(img)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
